package david.java.tools;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.HashMap;

/**
 * @Description:
 * @Author: ZhaoDawei
 * @Date: Create in 9:13 下午 2022/7/5
 */
public class Hive2KafkaCol {
    public static void main(String[] args) throws IOException {
        String input = "src/tmp/k2d";
        String output = "target-tmp2/tmp-k2d";
        mkdirIfNotExists(output);

        generate(input, output);
    }


    public static void generate(String input, String output) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(input));
        BufferedWriter bw = new BufferedWriter(new FileWriter(output));
        JSONArray jsonArray = new JSONArray();

        String line;

        while ((line = br.readLine()) != null) {
            if (StringUtils.isNotBlank(line)) {
                String[] split = line.split("\\s");
                boolean flag = true;
                HashMap<String, Object> map = null;
                inner:
                for (String str : split) {
                    // 过滤注释
                    if (str.startsWith("--")) {
                        break inner;
                    }
                    if (StringUtils.isNotBlank(str)) {
                        char[] chars = str.toCharArray();
                        StringBuilder sb = new StringBuilder();
                        for (char c : chars) {
                            if (c != '`' && c != ',') {
                                sb.append(c);
                            }
                        }
                        if (flag) {
                            map = new HashMap<>();
                            map.put("name", sb.toString());
                            flag = false;
                        } else {
                            map.put("type", sb.toString());
                            jsonArray.add(map);
                            break inner;
                        }
                    }
                }
            }
        }

        String jsonString = JSON.toJSONString(jsonArray, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat);
        bw.write(jsonString);

        bw.flush();
        br.close();
        bw.close();

    }

    private static void mkdirIfNotExists(String path) {
        File file = new File(path);
        String parent = file.getParent();
        if (parent.equals("/")) {
            return;
        }
        boolean exists = file.getParentFile().exists();
        if (!exists) {
            file.getParentFile().mkdirs();
        }
    }
}
